package com.data.mv.sql;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SqlCreateTable {
    public static String create(String tableName, List<Map<String, String>> pros) {
        StringBuilder sql = new StringBuilder("CREATE TABLE `" + tableName + "` (");

        pros.stream().forEach(pro -> {
            String columnName = pro.get("COLUMN_NAME");
            sql.append("`").append(columnName).append("`").append(" ");

            String dataType = SqlUtils.getMysqlDataType(pro.get("DATA_TYPE"), pro.get("DATA_LENGTH"));
            sql.append("OID".equals(columnName) ? "bigint" : dataType);
            if (!"int".equals(dataType) && !"datetime".equals(dataType)) {
                sql.append("(").append(pro.get("DATA_LENGTH")).append(")");
            }
            sql.append(" ");

            String nullable = pro.get("NULLABLE");
            if ("N".equals(nullable)) {
                sql.append("NOT NULL").append(" ");
            }

            if ("ID".equals(columnName)) {
                sql.append("AUTO_INCREMENT").append(" ");
                sql.append("PRIMARY KEY").append(" ");
            }

            if (Objects.nonNull(pro.get("DATA_DEFAULT")) && !pro.get("DATA_DEFAULT").startsWith("NULL")) {
                sql.append("DEFAULT '").append(pro.get("DATA_DEFAULT")).append("' ");
            }

            if (Objects.nonNull(pro.get("COMMENTS"))) {
                sql.append("COMMENT '").append(pro.get("COMMENTS")).append("'");
            }
            sql.append(",");
        });

        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        return sql.toString();
    }

}
